import { getToken } from 'Utils/cookies.js'
import allRoute from '../pageRoute';
import { getMenuList } from './MenuList'

async function beforeRoute (router) {
  let isF = false //判断是否以获取
  console.log(111, router);
  router.beforeEach(async (to, from, next) => {
    if (to.path == '/login' || to.path === '/') {
      next();
    } else {
      const token = getToken();
      if (!token) {
        next({ path: '/login' });
      } else {
        if (isF) {
          next();
        } else {
          let allRoutes = await getMenuList()
          //获取 menu菜单
          const currenRoutes = router.options.routes;
          console.log('存在的路由地址和菜单', currenRoutes);
          allRoutes.forEach(item => {
            const has = currenRoutes[2].children.some(it => it.path == item.path)
            if (!has) {
              currenRoutes[2].children.push(item)
            }
          })
          if (currenRoutes[currenRoutes.length - 1].path != '/:catchAll(.*)') {
            currenRoutes.push({ path: "/:pathMatch(.*)", redirect: "/404" });
          }
          // 将新生成的路由替换原路由1
          currenRoutes.forEach(item => {
            router.addRoute(item)
          })
          // 更改控制生成路由次数的值
          isF = true
          if (to.name === 'NotFound') { // 刷新时会丢失路由,定向到404后,重新执行跳转
            next({ path: to.path, query: to.query })
          } else {
            // 跳转
            //确保addRoute()时动态添加的路由已经被完全加载上去，不然刷新页面可能会导致空白
            next({ ...to, replace: true });
            // 当然在这一步也可以是去判断一下to.matched是否含有数据，如果没有再触发一次beforeEach
            if (to.matched.length == 0) {
              router.push(to.path)
            }
          }
        }
      }
    }
  }
  )
}

export default beforeRoute;